package com.seleniti.enpareja.web.desktop.client.ui.view;

import org.ioc.commons.flowcontrol.actioncontroller.IsExternalAction;
import org.ioc.commons.flowcontrol.eventbus.IsEvent;
import org.ioc.commons.flowcontrol.operationmanager.IsOperation;
import org.ioc.commons.impl.gwt.client.ui.ViewComposite;
import org.ioc.commons.ui.HasValue;
import org.ioc.commons.ui.IsViewPresenter;
import org.ioc.commons.ui.impl.HasValueAdapter;
import org.ioc.commons.utils.Format;

import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.Widget;
import com.seleniti.enpareja.controller.common.domain.UserAgent;
import com.seleniti.enpareja.controller.model.integration.database.domain.Couple;
import com.seleniti.enpareja.controller.ui.view.EnParejaView;
import com.seleniti.enpareja.web.appbase.client.model.UserAgentResolver;
import com.seleniti.enpareja.web.desktop.client.ui.resources.CommonResources;

abstract class EnParejaBaseView<E extends Enum<? extends IsEvent>, O extends Enum<? extends IsOperation>, A extends Enum<? extends IsExternalAction>, P extends IsViewPresenter>
		extends ViewComposite<E, O, A, P> implements EnParejaView<E, O, A> {

	@Override
	protected void initWidget(Widget widget) {
		super.initWidget(widget);

		if (UserAgentResolver.getUserAgent() == UserAgent.ANDROID_EMBEDDED_BROWSER) {
			widget.addStyleName(CommonResources.INSTANCE.style().android());
		}
	}

	@Override
	public HasValue<Couple> couple() {
		return HasValueAdapter.<Couple> forField("couple", this);
	}

	protected SafeHtml maskEmail(String email) {
		if (email != null) {
			String parts[] = email.split("@");
			String username = parts[0];
			String server = parts[1];

			boolean isMask = false;
			if (username.length() > 2) {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < username.length(); i++) {
					if (i == 0 || i == username.length() - 1) {
						if (isMask) {
							sb.append("</i>");
						}
						sb.append(username.charAt(i));
					} else {
						if (!isMask) {
							sb.append(Format
									.substitute(
											"<i class='{0}' title='Para proteger la privacidad, la dirección de correo de las personas que utilizan EnPareja.net permanece enmascarada'>",
											CommonResources.INSTANCE.style().mask()));
							isMask = true;
						}
						sb.append('x');
					}
				}
				username = sb.toString();
			}

			SafeHtmlBuilder sb = new SafeHtmlBuilder();
			sb.appendHtmlConstant(Format.substitute("{0}@{1}", username, server));
			return sb.toSafeHtml();
		} else {
			return null;
		}
	}
}
